package com.xiaoy.core.database.form.server;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springside.modules.orm.Page;

import com.google.common.collect.Lists;
import com.xiaoy.core.database.form.entity.Business;
import com.xiaoy.core.database.form.entity.Fetter;
import com.xiaoy.core.database.form.entity.Field;
import com.xiaoy.core.database.form.entity.View;
import com.xiaoy.core.database.form.vo.ViewTemplateData;
import com.xiaoy.dao.DaoUtil;

@Service
public class FetterService {
	
//	private FetterDao fetterDao;
	
	
	@Resource
	private DaoUtil dao;
	@Resource
	private ViewService viewService;
	@Resource
	private FieldService fieldService;
	
	public void save (Fetter fetter) {
//		fetterDao.save(fetter);
	}
	

	public ViewTemplateData parsing (Business business)throws Exception{
		
		if (business instanceof View) {
			return parsingView(business.getId());
		}
		throw new Exception();
	}
	
	public ViewTemplateData parsingView (long viewId){
		
//		View view = viewService.byId(viewId);
//		String sql = view.getSql();
		
		// 字段
		List<Field>fields = fieldService.getFieldsByBusinessId(viewId);
		// 搜索字段初始化
		List<Field>searchFields = Lists.newArrayList();
		for (Field f:fields) {
			if (f.getIsSearch() == "1") {
				searchFields.add(f);
			}
		}
		
		ViewTemplateData vtd = new ViewTemplateData();
		vtd.setSearchs(searchFields);
		vtd.setFields(fields);
		
		
		
		return vtd;
	}
	
	
	public void exe (long viewId,Map<String,Object>params) {
		
		View view = viewService.byId(viewId);
		String sql = view.getSql();
		Page page = new Page(view.getRowNum());
		//得到sql where条件的顺序
		int gourpIndex = sql.indexOf("group");
		int orderIndex = sql.indexOf("order");
		String where = "";
		if (gourpIndex == -1) {
			if (orderIndex==-1) {
				where = sql.substring(sql.indexOf("where")+6);
			}else {
				where = sql.substring(sql.indexOf("where")+6,orderIndex-1);
			}
		}else {
			where = sql.substring(sql.indexOf("where")+6,gourpIndex-1);
		}
		
		
		String temp = "1=1";
		List<Object> ps = Lists.newArrayList();
		// 拼装查询条件
		for (Entry<String, Object>e:params.entrySet()) {
			temp += " and "+e.getKey()+"=? ";
			ps.add(e.getValue());
		}
		
		sql.replace("$where", temp);
		
//		dao.query(page,sql,ps);
	}
	
//	public void encrypt (Business business,List<Field> fields){
//		
//		dao.save(business);
//		for (Field field : fields) {
//			field.setBusinessId(business.getId());
//			dao.save(field);
//		}
//	}
	
//	public void encryptView (View view){
//	}
}


